package com.kr.aia.powerrp.setting;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

//import com.kr.aia.powerrp.common.commonOnTouchListener;
import com.kr.aia.powerrp.db.CustomerDBUtil;
import com.kr.aia.powerrp.db.CustomerInfoVO;
import com.kr.aia.powerrp.db.UserDBUtil;
import com.kr.aia.powerrp.db.UserInfoVO;
import com.kr.aia.powerrp.R;

public class SettingMain extends Activity implements OnClickListener{
	private CustomerDBUtil custDataSource;
	private UserDBUtil userDataSource;
	
	UserInfoVO curUserInfo;
	
	private EditText userName;
	private EditText userPhoneNo;
	private EditText customerName;
	private EditText recommender;
	private EditText relation;
	private EditText customerPhoneNo;
    
	private Button goHome;
	private Button btn_save_user_info;
	private Button btn_seaerch_contact;
	private Button btn_seaerch;
	private Button btn_reset;
	private Button btn_save;
	private Button btn_delete;
	
	private ListView custListView;
	
	private ArrayList<CustomerInfoVO> custData;
	private ArrayAdapter<CustomerInfoVO> custAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_main);
        
        userName = (EditText) findViewById(R.id.txt_user_name);
		userPhoneNo = (EditText) findViewById(R.id.txt_user_phone_no);
		
		customerName = (EditText) findViewById(R.id.txt_customer_name);
		recommender = (EditText) findViewById(R.id.txt_recommender);
		relation = (EditText) findViewById(R.id.txt_relation);
		customerPhoneNo = (EditText) findViewById(R.id.txt_customer_phone_no);
        
        
        goHome = (Button) findViewById(R.id.btn_go_home_from_setting);
        btn_save_user_info = (Button) findViewById(R.id.btn_save_user_info);
        btn_seaerch_contact = (Button) findViewById(R.id.btn_seaerch_contact);
        btn_seaerch = (Button) findViewById(R.id.btn_seaerch);
        btn_reset = (Button) findViewById(R.id.btn_reset);
        btn_save = (Button) findViewById(R.id.btn_save);
        btn_delete = (Button) findViewById(R.id.btn_delete);
        
        
        
        userDataSource = new UserDBUtil(this);
		userDataSource.open();
        
        custDataSource = new CustomerDBUtil(this);
		custDataSource.open();
		
		
		// 사용자 정보 세팅
		curUserInfo = userDataSource.getAllData();
        if(curUserInfo != null){
        	userName.setText(curUserInfo.getUserName());
        	userPhoneNo.setText(curUserInfo.getUserPhoneNo());
        }
		
		// 우측 고객 리스트 세팅
		custData = custDataSource.getAllData();

		custListView = (ListView) findViewById(R.id.custListView);
		custAdapter = new CustomerListAdapter(this, R.layout.setting_contact_list_row, custData);
		custAdapter.setNotifyOnChange(true);
		custListView.setAdapter(custAdapter);
		
		
		custListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	CustomerInfoVO tmp = (CustomerInfoVO)parent.getAdapter().getItem(position);
            	((CustomerListAdapter) custAdapter).setSelectedItem(position);
            	
            	if(tmp.isSelected){
            		tmp.isSelected = false;
        		}else{
        			tmp.isSelected = true;
        		}
            	
            	customerName.setText(tmp.getCustomerName());
        		recommender.setText(tmp.getRecommender());
        		relation.setText(tmp.getRelation());
        		customerPhoneNo.setText(tmp.getCustomerPhoneNo());

            }
        });
        
        
        // 클릭 리스너 등록
        goHome.setOnClickListener(this);
        btn_save_user_info.setOnClickListener(this);
        btn_seaerch_contact.setOnClickListener(this);
        btn_seaerch.setOnClickListener(this);
        btn_reset.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        
        
        // 클릭 효과 세팅
        /*goHome.setOnTouchListener(new commonOnTouchListener());
        btn_save_user_info.setOnTouchListener(new commonOnTouchListener());
        btn_seaerch_contact.setOnTouchListener(new commonOnTouchListener());
        btn_seaerch.setOnTouchListener(new commonOnTouchListener());
        btn_reset.setOnTouchListener(new commonOnTouchListener());
        btn_save.setOnTouchListener(new commonOnTouchListener());
        btn_delete.setOnTouchListener(new commonOnTouchListener());
         */        
        
        // 전화번호 포멧 세팅
        userPhoneNo.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
        customerPhoneNo.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
        
        
        

    }
    
    
    @Override
    public void onClick(View v){
    	switch(v.getId()){
    		case R.id.btn_go_home_from_setting:
    			finish();
    			break;
    		case R.id.btn_save_user_info:
    			UserInfoVO newUserInfo = new UserInfoVO( userName.getText().toString(), userPhoneNo.getText().toString());
        		userDataSource.insertUserInfo(newUserInfo, curUserInfo);
    			break;
    		case R.id.btn_seaerch_contact:
    			ArrayList<ContactInfo> contactData = getContactList();
    			ContactListAdapter adapter = new ContactListAdapter(this, contactData);
    			
    			LayoutInflater inflater = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE));
    			View contactView = inflater.inflate(R.layout.setting_contact_list_popup_main, null, false);
    			
    			//View contactView =  
    				//getLayoutInflater().inflate(R.layout.setting_contact_list_popup_main, null ,false);
    			ListView contactList = (ListView) contactView.findViewById(R.id.list);
    			contactList.setAdapter(adapter);
    			
    			AlertDialog.Builder contactPopup = new AlertDialog.Builder(this);
    			contactPopup.setTitle("연락처 목록" + "(총 " + adapter.getCount() + "개)");
		   		contactPopup.setView(contactView);
		   		contactPopup.setPositiveButton("닫기", new DialogInterface.OnClickListener(){
		   			@Override
					public void onClick(DialogInterface dialog, int which) {
		   				dialog.dismiss();
		   			}
		   		});
		   		final Dialog dialog = contactPopup.create();
		   		dialog.show();
		   		
		   		contactList.setOnItemClickListener(new OnItemClickListener() {
    	            @Override
    	            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    	            	ContactInfo persons = (ContactInfo)parent.getAdapter().getItem(position);
    	            	((CustomerListAdapter) custAdapter).setSelectedItem(position);
    	            	
    	            	customerName.setText(persons.getContactName());
    	        		recommender.setText("");
    	        		relation.setText("");
    	        		customerPhoneNo.setText(persons.getContactPhoneNo());
    	        		
    	        		dialog.dismiss();
    	            }
    	        });
		   		
		   		
    			break;
    		case R.id.btn_seaerch:
    			break;
    		case R.id.btn_reset:
    			customerName.setText("");
        		recommender.setText("");
        		relation.setText("");
        		customerPhoneNo.setText("");
        		((CustomerListAdapter) custAdapter).setSelectedItem(-1);
        		custAdapter.notifyDataSetChanged();
    			break;
    		case R.id.btn_save:
    			if(!customerName.getText().toString().equals("")){
    				CustomerInfoVO ci = new CustomerInfoVO();
    				
	    			ci.setCustomerName(customerName.getText().toString());
	    			ci.setCustomerPhoneNo(customerPhoneNo.getText().toString());
	    			ci.setRecommender(recommender.getText().toString());
	    			ci.setRelation(relation.getText().toString());
	    			
	    			int returnID = (int) custDataSource.insertCustInfo(ci) -1;
	    			if(returnID > -1){
	    				custData.add(ci);
	    				((CustomerListAdapter) custAdapter).setSelectedItem(returnID);
	    				custAdapter.notifyDataSetChanged();
	    				custListView.setSelection(returnID);
	    			}
    			}
    			break;
    		case R.id.btn_delete:
    			
    			try{
    				for(int i = 0 ; i < ((CustomerListAdapter) custAdapter).getCount() ; i++){
        				if(((CustomerListAdapter) custAdapter).getItem(i).isSelected){
        					custDataSource.deleteCustInfo(((CustomerListAdapter) custAdapter).getItem(i));
        					custData.remove(i);
        				}
        			}
        			Toast.makeText(getApplicationContext(), "삭제 되었습니다.", Toast.LENGTH_SHORT).show();
        			custAdapter.notifyDataSetChanged();
        			
    			}catch(Exception e){
    				Toast.makeText(getApplicationContext(), "삭제 실패! 다시 시도하세요.", Toast.LENGTH_SHORT).show();
    			}
    			
    			break;
    		default:
    			break;
    	}
    }
    
    
    
    public ArrayList<ContactInfo> getContactList(){
    	
    	Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    	
    	String[] projection = new String[] {   			
    			ContactsContract.CommonDataKinds.Phone.NUMBER,
    			ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
    	};
    	
    	String[] selectionArgs = null;

    	//정렬
    	String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
    	//조회해서 가져온다
    	Cursor contactCursor = managedQuery(uri, projection, null, selectionArgs, sortOrder);
    	
        //정보를 담을 array 설정
    	ArrayList<ContactInfo> persons = new ArrayList<ContactInfo>();

    	if(contactCursor.moveToFirst()){    	
	    	do{
	    		ContactInfo tmp = new ContactInfo();
	    		tmp.setContactName(contactCursor.getString(1));
	    		tmp.setContactPhoneNo(contactCursor.getString(0));
	    		persons.add(tmp);
	    	}while(contactCursor.moveToNext());
    	}
    	
    	return persons;
    }
    
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
            	recorderController.startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                recorderController.releaseMediaRecorder();
            }
            break;

        case 1: //GoToAllNotes
        	recorderController.stopRecording();
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    */
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	Log.e("PRP", "Closing DB..");
    	userDataSource.close();
        custDataSource.close();
    }
    
}